<template>
    <div
        class="contract-detial-page contract-cancellation-detial"
        :class="readOnly ? 'read':'write'"
    >
        <Card>
            <Affix :offset-top="120">
                <div class="contract-detial-affix">
                    <div style="text-align: left;"
                         v-if="this.params.editFlag && this.params.processStatus!=='draft' && this.params.processStatus!=='toBeRepaired'
                         && this.params.processStatus!=='payment' && this.params.processStatus!=='toBePaymentUnderReview'">
                        <Button type="primary" @click="back()">返回</Button>
                        <Button type="primary" v-if="!readOnly" @click="checkPenalty('pass')">通过</Button>
                        <Button type="primary" v-if="!readOnly" @click="approve('return')">退回</Button>
                        <Button type="primary" v-if="!readOnly" @click="approve('reject')">拒绝</Button>
                    </div>
                    <div style="text-align: right;" v-else>
                        <Button type="primary" @click="back()">返回</Button>
                        <Button type="primary" v-if="!readOnly" @click="handleSubmit">保存</Button>
                        <Button type="primary" v-if="!readOnly" @click="submit">提交</Button>
                    </div>
                </div>
            </Affix>
            <Form
                ref="contractForm"
                :model="contractForm"
                :rules="contractFormValidate"
                :label-width="100"
            >
                <Collapse v-model="openPanel">
                    <Panel name="0" v-if="!this.isSP && this.params.editFlag">
                        <!-- <Alert>日志信息</Alert> -->
                        日志信息
                        <div class="content" slot="content">
                            <approveHistory :Obj="Obj"/>
                        </div>
                    </Panel>
                    <Panel name="1">
                        <!-- <Alert>基本信息</Alert> -->
                        基本信息
                        <div class="content" slot="content">
                            <BaseInfo ref="baseInfo" :formData="pageInfo"/>
                        </div>
                    </Panel>
                    <Panel name="2">
                        <!-- <Alert>合同信息</Alert> -->
                        合同信息
                        <div class="content" slot="content">
                            <contractInfo
                                :Obj="Obj"
                                :readOnly="readOnly"
                                ref="contractInfo"
                                type="cancelContract"
                            />
                        </div>
                    </Panel>
                    <Panel name="4">
                        <!-- <Alert>金融产品</Alert> -->
                        金融产品
                        <div class="content" slot="content">
                            <FinanceInfo ref="financeInfo" :Obj="Obj"/>
                        </div>
                    </Panel>
                    <Panel name="5">
                        <!-- <Alert>资产信息</Alert> -->
                        资产信息
                        <div class="content" slot="content">
                            <CustAssetInfo :Obj="Obj" type="cancelContract"/>
                        </div>
                    </Panel>
                    <Panel name="6" v-if="this.affiliatedType">
                        <!-- <Alert>挂靠信息</Alert> -->
                        挂靠信息
                        <div class="content" slot="content">
                            <CustAnchorInfo ref="anchor" @affType="affType" :Obj="Obj"/>
                        </div>
                    </Panel>
                    <Panel name="7">
                        <!-- <Alert>业务办理</Alert> -->
                        业务办理
                        <div class="content" slot="content">
                            <Business ref="business" :Obj="Obj" :readOnly="readOnly"/>
                        </div>
                    </Panel>
                    <Panel
                        v-if="(this.params.creditStatus==='successPayment'&&this.params.processStatus==='approved')||this.params.processStatus==='payment'||this.params.processStatus==='toBePaymentUnderReview'||this.params.processStatus==='paymentUnderReview'"
                        name="8">
                        <!-- <Alert>已放款项退回</Alert> -->
                        已放款项退回
                        <div class="content" slot="content">
                            <Refunded ref="refunded"
                                      :readOnly="readOnly"
                                      @submitDataFn="submitDataFn"
                                      @childBusinessForm="childBusinessForm"
                                      :Obj="Obj"
                                      :id="id"
                                      :dataDict="dataDict"
                                      @changeAmount="changeAmount"
                                      @changeHandle="changeHandle"
                            />
                        </div>
                    </Panel>
                    <Panel
                        v-if="isFinance||(this.params.creditStatus==='successPayment'&&this.params.processStatus==='approved')"
                        name="9">
                        <!-- <Alert>网银到账查询</Alert> -->
                        网银到账查询
                        <div class="content" slot="content">
                            <ArrivalInquiry ref="arrivalInquiry" :Obj="Obj" :dataDict="dataDict"/>
                        </div>
                    </Panel>
                    <Panel name="10"
                           v-if="(!readOnly && this.params.editFlag && this.params.processStatus!=='draft' && this.params.processStatus!=='toBeRepaired'
                                  && this.params.processStatus!=='payment' && this.params.processStatus!=='toBePaymentUnderReview')||this.params.processStatus==='approved'">
                        <!-- <Alert>当前用户: {{userInfo ? userInfo.userRealName :''}}</Alert> -->
                        当前用户: {{userInfo ? userInfo.userRealName :''}}
                        <div class="content" slot="content">
                            <ContractCurrentUser ref="contractCurrentUser" :Obj="Obj" @childUserForm="childUserForm"/>
                        </div>
                    </Panel>
                </Collapse>
            </Form>
        </Card>
        <Spin size="large" fix v-if="spinShow"></Spin>
    </div>
</template>
<script>
    import {mapGetters} from "vuex";
    import {
        findByIdDetails,
        saveProposalApplicationInfo,
        submit,
        submitCancelRecord
    } from "_p/basic/api/contract/contract-cancel/index";
    import {checkFile} from "_p/basic/api/image/image-upload";
    import {businessSource, channelType, Finance, FinanceType} from "_p/basic/api/contract/channel-type/channel-type";
    import {getDictDataList, sub} from "_p/basic/assets/contract/js/utils";
    import {findByContractNo} from "_p/basic/api/contract/activated-case/index";
    // 已放款项退回
    import Refunded from "./Refunded";
    // 业务办理
    import Business from "./Business";
    // 网银到账查询
    import ArrivalInquiry from "./ArrivalInquiry";
    // 基本信息
    import BaseInfo from "_p/basic/pages/contract/common/base-info";
    // 金融产品
    import FinanceInfo from "_p/basic/pages/contract/common/finance-info/finance-info";
    // 资产信息
    import CustAssetInfo from "_p/basic/pages/contract/common/cust-asset/custAssetInfo";
    // 合同信息
    import contractInfo from "_p/basic/pages/contract/common/contract-info/contract-info";
    // 挂靠信息
    import CustAnchorInfo from "_p/basic/pages/contract/common/cust-anchor/custAnchorInfo";
    // 日志信息
    import approveHistory from "_p/basic/pages/contract/common/approve-history/approve-history";
    // 当前用户
    import ContractCurrentUser from "_p/basic/pages/contract/common/current-user/contractCurrentUser";

    export default {
        // 合同取消详情
        name: "ContractCancellationDetial",
        components: {
            Refunded,
            BaseInfo,
            Business,
            FinanceInfo,
            contractInfo,
            CustAssetInfo,
            CustAnchorInfo,
            ArrivalInquiry,
            approveHistory,
            ContractCurrentUser
        },
        data() {
            return {
                name: null,
                flag: true,
                overpaymentFlag: false,
                spinShow: false,
                type: null,
                params: {},
                readOnly: null,
                contractBusiness: ["repaymentDateChange", "corporateSettlementPrepayment", "corporateSettlementRent", "bankCardChange", "custInfoChange"
                    , "assetsChange", "advanceSettle", "reprintContract", "costExemptBill", "exemptTypes", "costExempt"],
                affiliatedType: null,
                pageParams: {},
                contractNo: null,
                creditStatus: null,
                paymentStatus: null,
                customerInfo: {},
                Obj: {},
                caseNo: null,
                id: null,
                loading: true,
                defaultContractData: {},
                contractForm: {},
                contractFormValidate: {},
                pageInfo: {},
                // 数据字典
                dicttArr: [
                    "AccountRegistStatus", "certType", "PersonRoleType", "payBank", "processMode", "repaymentBank"
                ],
                // selct 数据字典
                dataDict: {},
                modalType: "",
                modalTitle: "",
                modal: false,
                openPanel: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]
            };
        },
        computed: {
            ...mapGetters({userInfo: "userInfo", roleType: "roles"}),
            // 是否是合作商
            isSP: function () {
                return channelType(this.roleType)
                // return true;
            },
            isFinanceType: function () {
                return FinanceType(this.roleType)
            },
            isFinance: function () {
                return Finance(this.roleType)
            },
        },
        created() {
            this.getParams();
        },
        mounted() {
            this.getDictDataList();
            if (this.params.editFlag) {
                this.findByIdDetails();
            }
            this.init();
        },

        methods: {
            init() {
            },
            // 获取初始数据
            getParams() {
                const params = this.afs.getPageParams(this);
                this.params = params;
                this.type = params.type;
                this.readOnly = params.type === "read" ? true : false;
                this.contractNo = params.contractNo;
                this.caseNo = params.caseNo;
                console.log("params",params)
                this.contractForm.dataSource = params.dataSource
                if (params.bizDataId === undefined) {
                    this.id = params.id;
                } else {
                    this.id = params.bizDataId;
                }
                this.Obj = {
                    isFinance: this.isFinance,
                    roleType: this.isSP,
                    caseNo: params.caseNo,
                    contractNo: params.contractNo,
                    processStatus: params.processStatus,
                    type: 'cancelContract'
                }
            },
            findByIdDetails() {
                findByIdDetails(this.caseNo).then(res => {
                    if (res.code === "0000") {
                        this.creditStatus = res.data.creditStatus;
                        this.pageInfo = res.data;
                        this.$refs.business.formData = res.data;
                        if (this.$refs.refunded) {
                            this.$refs.refunded.formData = res.data;
                        }
                        if (res.data.amtHandle === 'TAKE_BACK') {
                            this.overpaymentFlag = true;
                        }
                    }
                });
            },
            affType(type) {
                this.affiliatedType = type;
            },
            changeAmount(amount) {
                this.$refs.refunded.formData.balanceAmt = sub(amount, this.$refs.financeInfo.formData.basicPaymentPool.paymentAmt);
            },
            changeHandle(flag) {
                this.overpaymentFlag = flag;
            },
            formData() {
                this.contractForm.applyNo = this.$refs.contractInfo.formData.applyNo;
                this.contractForm.contractNo = this.$refs.contractInfo.formData.contractNo;
                this.contractForm.custName = this.$refs.contractInfo.formData.basicCustBaseInfo.custName;
                this.contractForm.startDate = this.$refs.contractInfo.formData.startDate;
                this.contractForm.contractStatus = this.$refs.contractInfo.formData.contractStatus;
                this.contractForm.channelFullName = this.$refs.contractInfo.formData.channelFullName;
                this.contractForm.channelType = this.$refs.contractInfo.formData.channelBelong;
                this.contractForm.contactNo = this.$refs.contractInfo.formData.basicCustBaseInfo.phone;
                this.paymentStatus = this.$refs.financeInfo.formData.basicPaymentPool.paymentStatus;
                if (this.$refs.refunded !== undefined) {
                    this.contractForm = Object.assign({}, this.contractForm, this.$refs.refunded.formData);
                } else {
                    this.contractForm = Object.assign({}, this.contractForm, this.$refs.business.formData);
                }
                if (this.isSP) {
                    this.contractForm.department = this.$refs.contractInfo.channelFullName;
                } else {
                    this.contractForm.department = this.userInfo.userRealName;
                }
                this.contractForm.creditStatus = this.$refs.financeInfo.formData.basicPaymentPool.paymentStatus;
                this.contractForm.remarks = this.$refs.business.formData.remarks;
                if (this.$refs.contractCurrentUser !== undefined) {
                    this.contractForm.reasonType = this.$refs.contractCurrentUser.formData.reasonType;
                    this.contractForm.approvalOpinion = this.$refs.contractCurrentUser.formData.approvalOpinion;
                }
                this.contractForm.businessSource = businessSource(this.roleType);
                if (this.$refs.arrivalInquiry) {
                    this.contractForm.accountRegisterList = this.$refs.arrivalInquiry.formData.accountRegister;
                }
                return this.contractForm;
            },
            handleSubmit() {
                if (this.readOnly) return;
                this.formData();
                submit(this.contractForm)
                    .then(res => {
                        if (res.code === "0000") {
                            this.$Message.success("保存成功!");
                            this.pageInfo = res.data;
                            if (this.$refs.refunded !== undefined) {
                                this.$refs.refunded.formData = res.data;
                            }
                            this.$refs.business.formData = res.data;
                        }
                    })
                    .catch(e => {
                        this.$Message.error("保存失败!");
                        console.log(e);
                    });
            },
            getDictDataList() {
                getDictDataList(this.dicttArr).then(res => {
                    this.dataDict = res;
                });
            },
            back() {
                //关闭页面
                this.afs.closeTab(this);
            },
            submit() {
                if (this.$refs.refunded !== undefined) {
                    let contractAmt = this.$refs.financeInfo.formData.basicPaymentPool.paymentAmt;
                    let amount = this.$refs.refunded.formData.amount;
                    if (contractAmt > amount) {
                        this.$Modal.warning({
                            title: "警告",
                            content: "不能小于实际放款金额，请核实"
                        });
                        return;
                    }
                }
                this.checkFile();
            },
            checkFile() {
                let params;
                if (this.$refs.refunded) {
                    params = {
                        busiNo: this.$refs.business.formData.caseNo,
                        busiType: "overpayment",
                    };
                } else {
                    params = {
                        busiNo: this.$refs.business.formData.caseNo,
                        busiType: "cancelContract",
                    };
                }
                checkFile(params).then(res => {
                    if (res.code === "0000") {
                        this.findByContractNo();
                    }
                })
            },
            findByContractNo() {
                let params = {
                    contractBusiness: ["cancelContract"],
                    contractNo: this.contractNo,
                    handleBusiness: "cancelContract",
                    isSP: this.isSP
                };
                if (this.params.processStatus === 'draft') {
                    findByContractNo(params).then(res => {
                        if (res.code === "0000") {
                            if (res.msg === "success") {
                                this.fnSubmit();
                            }
                        }
                    });
                } else {
                    this.fnSubmit();
                }
            },
            fnSubmit() {
                let data = this.formData();
                data.approvalOperating = 'suggestCheckF';
                if (this.$refs.refunded) {
                    // 验证 refunded 组件数据 给下一个方法
                    this.$refs.refunded.formValidate("submitDataFn", data);
                } else {
                    this.submitDataFn(data);
                }
            },
            submitDataFn(data) {
                if (!data) return;
                this.$Modal.confirm({
                    title: "确认提交？",
                    onOk: () => {
                        this.submitCancelRecord(data);
                    }
                });
            },
            submitCancelRecord(data) {
                submitCancelRecord(data).then(res => {
                    if (res.code === "0000") {
                        this.$Message.success(res.msg);
                        this.back();
                    }
                });
            },
            checkPenalty(name) {
                findByContractNo({
                    contractBusiness: this.contractBusiness,
                    contractNo: this.contractNo,
                    handleBusiness: "cancelContract",
                    isSP: this.isSP
                }).then(res => {
                    if (res.code === "0000") {
                        if (res.msg === "success") {
                            this.approve(name);
                        }
                    }
                })
            },
            // 审核等按钮
            approve(name) {
                if (name == 'pass' && this.$refs.arrivalInquiry !== undefined && this.isFinanceType) {
                    if (this.$refs.arrivalInquiry.formData.accountRegister === undefined) {
                        this.$Modal.warning({
                            title: "警告",
                            content: "请确认到账情况，勾稽到账数据！"
                        });
                        return;
                    }
                }
                if (!name) return;
                let t, val;
                switch (name) {
                    case "pass":
                        t = "通过";
                        val = "suggestCheckF";
                        break;
                    case "return":
                        t = "退件";
                        val = "sendBack";
                        break;
                    case "reject":
                        t = "拒绝";
                        val = "suggestRejectF";
                        break;
                }
                let data = this.formData();
                this.name = name;
                data.approvalOperating = val;
                if (this.$refs.refunded) {
                    // 验证 business 组件数据 给下一个方法
                    this.$refs.refunded.formValidate("childBusinessForm", data);
                } else {
                    this.childBusinessForm(data)
                }
            },
            // 审批 请求
            // Business 组件数据
            childBusinessForm(data) {
                if (!data) return;
                // 验证 contractCurrentUser 组件数据 传给下个方法
                this.$refs.contractCurrentUser.formValidate("childUserForm", data, this.name);
            },
            childUserForm(data) {
                if (!data) return;
                let t;
                switch (data.approvalOperating) {
                    case "suggestCheckF":
                        t = "通过";
                        break;
                    case "sendBack":
                        t = "退件";
                        break;
                    case "suggestRejectF":
                        t = "拒绝";
                        break;
                }
                this.$Modal.confirm({
                    title: `确认${t}？`,
                    onOk: () => {
                        this.approved(data)
                    }
                });
            },
            approved(data) {
                saveProposalApplicationInfo(this.contractForm).then(res => {
                    if (res.code === "0000") {
                        this.$Message.success(res.msg);
                        this.back();
                    }
                });
            },
            // 获取客户信息数据
            getCustomerInfoData(data) {
                this.customerInfo = data;
            },
        }
    };
</script>
<style lang="less">
    @import url("../../../../styles/common/form.less");

    .contract-cancellation-detial-btns {
        padding-bottom: 16px;
    }

    .contract-cancellation-detial {
        .ivu-collapse-header {
            background-color: #f0faff;
        }
    }
</style>
